package apps

import (
	"fmt"
	"news/pkg/apps/ctx"
	"news/pkg/models"
	"news/pkg/services"
	"news/pkg/types"
	"news/pkg/types/errors"
)

func AddSensitiveWord(c *ctx.Context, form *types.AddSensitiveWordForm) (interface{}, error) {
	sens, err := services.GetSensitiveByWord(c.DB(), form.Word)
	if err != nil {
		return nil, err
	}
	if sens != nil {
		return nil, errors.ErrAlreadyExists
	}
	sensword, err := services.CreateSensitive(c.DB(), form)
	if err != nil {
		return nil, err
	}
	return sensword, nil
}

func DeleteSensById(c *ctx.Context, id models.Id) (interface{}, error) {
	sens, err := services.GetSensitiveById(c.DB(), id)
	if err != nil {
		return nil, err
	}
	if sens == nil {
		return nil, errors.ErrNotFound
	}
	err = services.DeleteSensById(c.DB(), id)
	if err != nil {
		return nil, err
	}
	return nil, nil
}

func DeleteSensByIds(c *ctx.Context, form *types.DeleteSensForm) (interface{}, error) {
	err := services.DeleteSensByIds(c.DB(), form.Ids)
	if err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return nil, nil
}

func UpdateSens(c *ctx.Context, form *types.UpdateSensForm) (interface{}, error) {
	sens, err := services.GetSensitiveByWord(c.DB(), form.Word)
	if err != nil {
		return nil, err
	}
	if sens != nil {
		return nil, errors.ErrAlreadyExists
	}
	sens, err = services.GetSensitiveById(c.DB(), form.Id)
	if err != nil {
		return nil, err
	}
	sens, err = services.UpdateSensitive(c.DB(), form)
	if err != nil {
		return nil, err
	}
	return sens, nil

}

func QuerySensWords(c *ctx.Context, form *types.QuerySensWordForm) (interface{}, error) {
	query := services.QuerySensWords(c.DB(), form)
	sensWords := make([]models.Sensitive, 0)
	if err := query.Find(&sensWords).Error; err != nil {
		return nil, errors.AutoDbErr(err)
	}
	return c.PageResult(query, form.Page(), form.PageSize(), &sensWords)
}

func QuerySensWordsArry(c *ctx.Context, form *types.QuerySensWordForm) (interface{}, error) {
	query := services.QuerySensWords(c.DB(), form)
	sensWords := make([]string, 0)
	if err := query.Debug().Select("word").Find(&sensWords).Error; err != nil {
		fmt.Println("err is here")
		return nil, errors.AutoDbErr(err)
	}
	return sensWords, nil
}
